package com.argrace.smart.activity;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.SystemClock;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.util.Log;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.alink.business.alink.ALinkBusinessEx;
import com.aliyun.alink.business.downstream.DeviceBusiness;
import com.aliyun.alink.sdk.net.anet.api.AError;
import com.aliyun.alink.sdk.net.anet.api.persistentnet.EventDispatcher;
import com.aliyun.alink.sdk.net.anet.api.persistentnet.IOnPushListener;
import com.aliyun.alink.sdk.net.anet.api.transitorynet.TransitoryRequest;
import com.aliyun.alink.sdk.net.anet.api.transitorynet.TransitoryResponse;
import com.argrace.smart.R;
import com.argrace.smart.adapter.DeviceAdapter;
import com.argrace.smart.adapter.ZigBeeDeviceAdapter;
import com.argrace.smart.base.BaseActivity;
import com.argrace.smart.entity.ZigBeeDeviceEntity;
import com.argrace.smart.event.EventBusEvent;
import com.argrace.smart.recieve.TuiSongRecieve;
import com.argrace.smart.ui.EmptyRecycleView;
import com.argrace.smart.util.AlinkHttpUtil;
import com.bigkoo.svprogresshud.SVProgressHUD;
import com.chad.library.adapter.base.BaseQuickAdapter;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * Created by argrace_dev_1 on 2018/1/31.
 * 厂商的产品列表,也就是zigbee设备列表
 */

public class ProductListActivity extends BaseActivity implements SwipeRefreshLayout.OnRefreshListener, BaseQuickAdapter.RequestLoadMoreListener {
    EmptyRecycleView recyclerView;
    SwipeRefreshLayout refreshLayout;
    private ZigBeeDeviceAdapter adapter;
    private ArrayList<ZigBeeDeviceEntity> lists = new ArrayList<>();
    private ArrayList<ZigBeeDeviceEntity> lists_subdevice = new ArrayList<>();

    private String uuid, model;
    BroadcastReceiver receiver;
    private int subdevice_num;
    private SVProgressHUD mSVProgressHUD;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_productlist);
        init();
        initPushTunnel();
    }

    private DeviceBusiness deviceBiz = null;

    private void initPushTunnel() {

    }

    private void init() {
        uuid = getIntent().getStringExtra("uuid");
        model = getIntent().getStringExtra("model");
        subdevice_num = getIntent().getIntExtra("length", 0);
        Log.i("info", "ProductListActivity.init(),uuid = " + uuid + "---model=" + model);
        setTitle(true, false, "产品的设备列表");
        mSVProgressHUD = new SVProgressHUD(this);
        setView();
        onRefresh();
    }

    private void setView() {
        recyclerView = (EmptyRecycleView) findViewById(R.id.recyclerView);
        refreshLayout = (SwipeRefreshLayout) findViewById(R.id.refreshLayout);
        recyclerView.setItemAnimator(new DefaultItemAnimator());
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        adapter = new ZigBeeDeviceAdapter(lists, this);
        adapter.openLoadAnimation(BaseQuickAdapter.ALPHAIN);
        recyclerView.setAdapter(adapter);
//        refreshLayout.setColorSchemeColors(getResources().getColor(R.color.colorTheme), getResources().getColor(R.color.colorTheme), getResources().getColor(R.color.colorTheme));//getResources().getColor(R.color.colorTheme), getResources().getColor(R.color.colorTheme), getResources().getColor(R.color.colorTheme)
        refreshLayout.setOnRefreshListener(this);
        adapter.setListeners(new ZigBeeDeviceAdapter.OnAdapterItemClickListener() {
            @Override
            public void click(ZigBeeDeviceEntity bean, int position) {
                registerZigBeeDevice(bean.getShortModel());
            }
        });

    }


    private void getProductList() {
        Log.i("info", "ProductListActivity.getProductList()start");
        String method = "mtop.openalink.app.product.list";
        HashMap<String, Object> params = new HashMap<>();
        //产品类型，空值拉取全部model，sds仅拉取sds model,非必填
//        params.put("sourceCloudProduct", "1");
        AlinkHttpUtil.AlinkHttpRequest(method, params, new ALinkBusinessEx.IListener() {
            @Override
            public void onSuccess(TransitoryRequest transitoryRequest, TransitoryResponse transitoryResponse) {
                setRefreshing(false);
                lists.clear();
                Log.i("info", "获取产品列表成功" + transitoryResponse.data);
                List<ZigBeeDeviceEntity> beans = JSON.parseArray((String) transitoryResponse.data, ZigBeeDeviceEntity.class);
                lists.addAll(beans);
                adapter.notifyDataSetChanged();
            }

            @Override
            public void onFailed(TransitoryRequest transitoryRequest, AError aError) {
                Log.i("info", "获取产品列表失败" + aError.getMsg() + aError.getCode());
                setRefreshing(false);
            }
        });
    }

    //请求设备服务接口
    private void registerZigBeeDevice(String shortmodel) {
        Log.i("info", "ProductListActivity.registerZigBeeDevice()start,uuid = " + uuid + "---shortmodel" + shortmodel);
        String method = "mtop.openalink.app.core.device.requestremoteservice";
        HashMap<String, Object> params = new HashMap<>();
        //产品类型，空值拉取全部model，sds仅拉取sds model,非必填
        params.put("uuid", uuid);
        //这种参数表示子设备注册，发送云端后，云端会通知网关,shortModel为设备标识
        params.put("service", "PermitJoin");
        params.put("args", "{\"enable\":\"1\",\"duration\":\"120\",\"shortModel\":\" " + shortmodel + "\"}");
        AlinkHttpUtil.AlinkHttpRequest(method, params, new ALinkBusinessEx.IListener() {
            @Override
            public void onSuccess(TransitoryRequest transitoryRequest, TransitoryResponse transitoryResponse) {
                Log.i("info", "请求设备服务成功" + transitoryResponse.data);
                mSVProgressHUD.showWithStatus("设备扫描中，请操作子设备...");
            }

            @Override
            public void onFailed(TransitoryRequest transitoryRequest, AError aError) {
                Log.i("info", "请求设备服务失败,msg" + aError.getMsg() + aError.getCode() + "---" + aError.getSubCode());
                toastActBtm("请求设备服务失败");
            }
        });
    }

    private void startCheckLength() {
        Log.i("info", "SubDeviceListActivity.getSubDevicelist(),start,uuid = " + uuid);
        String method = "mtop.openalink.home.device.infolist";
        HashMap<String, Object> params = new HashMap<>();
        params.put("uuid", uuid);
        params.put("pageNo", "1");
        params.put("pageSize", "20");
        AlinkHttpUtil.AlinkHttpRequest(method, params, new ALinkBusinessEx.IListener() {
            @Override
            public void onSuccess(TransitoryRequest transitoryRequest, TransitoryResponse transitoryResponse) {
                setRefreshing(false);
                lists_subdevice.clear();
                JSONObject dataObj = JSON.parseObject(transitoryResponse.data.toString());
                List<ZigBeeDeviceEntity> beans = JSON.parseArray(dataObj.getString("deviceList"), ZigBeeDeviceEntity.class);
                lists_subdevice.addAll(beans);
                if (lists_subdevice.size() == subdevice_num) {
//                    SystemClock.sleep(500);
//                    startCheckLength();
                } else {
                    toastActBtm("设备添加成功");
                }

            }

            @Override
            public void onFailed(TransitoryRequest transitoryRequest, AError aError) {
                setRefreshing(false);
            }
        });
    }

    @Override
    public void onRefresh() {
        getProductList();
    }

    @Override
    public void onLoadMoreRequested() {
        getProductList();
    }

    public void setRefreshing(final boolean refreshing) {
        refreshLayout.post(new Runnable() {
            @Override
            public void run() {
                refreshLayout.setRefreshing(refreshing);
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Override
    protected void dorecieve(JSONObject obj) {
        super.dorecieve(obj);
        try {
            String value = obj.getJSONObject("params").getJSONObject("data").getJSONObject("Refresh").getString("value");
            //2说明是子设备入网成功推送
            if (value != null && value.equals("2")) {
                //子设备入网成功操作
                finish();
            }
        } catch (Exception e) {

        }
    }
}
